package com.wxgo.controller.admin;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.wxgo.common.model.Module;
import com.wxgo.utils.MenuUtils;

public class PowerController extends Controller {

	@SuppressWarnings("unchecked")
	public void manage() {
		String rid = getPara("rid");
		setAttr("rid", rid);
		// 获取当前用户的权限
		List<Record> powerList = Db.find("select mid from power where rid=? ", rid);
		List<Integer> midList = new ArrayList<Integer>(powerList.size());
		for (Record record : powerList) {
			midList.add(record.getInt("mid"));
		}
		String midStrs = this.listToStr(midList);
		setAttr("midArr", midStrs);
		Map<String, Object> ModuleMap = MenuUtils.getAllMenuList();
		List<Module> mModule = (List<Module>) ModuleMap.get("mMenus");
		Map<Integer, List<Module>> cModuleMap = (Map<Integer, List<Module>>) ModuleMap.get("cMenuMap");
		setAttr("mMenus", mModule);
		setAttr("cMenuMap", cModuleMap);
		render("/admin/power/power.html");
	}

	public void update() {
		Integer rid = getParaToInt("rid");
		Integer mid = getParaToInt("mid");
		Boolean isCheck = getParaToBoolean("isCheck");
		Record record = Db.findFirst("select rid,mid,id from power where rid=?  and mid=?", rid, mid);
		if (record != null && record.get("id") != null && !isCheck) {
			Db.delete("power", record);
		} else if (record == null && isCheck) {
			record = new Record().set("rid", rid).set("mid", mid);
			Db.save("power", record);
		}
		renderText("1");
	}

	private String listToStr(List<Integer> list) {
		String str = "{\"midArr\":[";
		for (Integer mid : list) {
			str += "{\"mid\":";
			str += mid;
			str += "},";
		}
		str = str.substring(0, str.length() - 1);
		str += "]}";
		return list.size() > 0 ? str : null;
	}
}
